#pragma once
#include <map>
#include "base/RefCounted.h"
#include "MessageLoop.h"
#include "MessageLoopProxy.h"
#include "Thread.h"
#include "base/Singleton.h"

namespace xBase
{
    class BASE_API CxThreadMgr : public CRefCountedThreadSafe<CxThreadMgr>
    {
    public:
        CxThreadMgr();
        ~CxThreadMgr();

        BOOL    AttachThread(DWORD dwThreadId, LOOP_TYPE type, std::string strDescription = "No Description");
        BOOL    DetachThread(DWORD dwThreadId);

        BOOL    RunMessageLoop();

        BOOL    PostTask(INT nType,CTask* pTask, INT64 delay = 0);
        BOOL    PostTaskByThreadId(DWORD dwThreadId, CTask* pTask, INT64 delay = 0);

        BOOL    StartThread(LPCSTR name, LOOP_TYPE type, DWORD* pTid);
        BOOL    StopThread(DWORD tid);

        typedef struct _thread_data
        {
            LOOP_TYPE                           type;
            DWORD                               dwThreadId;
            bool                                bAttach;
            CxMessageLoop*                      pMsgLoop;
            CScopedRefPtr<CxMessageLoopProxy>   pMsgLoopProxy;
            CxThread*                           pThread;
            std::string                         strDescription;

            _thread_data()
            {
                type            = LOOP_TYPE_DEFAULT;
                dwThreadId      = 0;
                bAttach         = false;
                pMsgLoop        = NULL;
                pThread         = NULL;
            }

        }*LPThreadData, ThreadData;

    private:
        typedef std::map<DWORD, ThreadData> ThreadDataMap;

        ThreadDataMap   m_mapThreadData;
        CxLock          m_olock;

        DECLARE_SINGLETON_CLASS(CxThreadMgr)
    };

    typedef TxSingleton<CxThreadMgr> ThreadMgr;
}